package com.example.oracle.controller;

import com.example.oracle.pojo.User;
import com.example.oracle.pojo.system.ResponseMap;
import com.example.oracle.pojo.system.WebCode;
import com.example.oracle.service.UserService;
import com.example.oracle.tool.JwtUtil;
import com.example.oracle.tool.MailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * @author Siaze
 * @date 2021/11/9
 */
@RestController
public class Common {
    private static final String REGISTER_FORMAT = "学号：%d, 姓名：%s，该用户请求注册用户。";
    @Autowired
    UserService userService;

    @Autowired
    MailUtil mailUtil;
    /**
     * 登录
     * @param params 用户请求的参数
     * @return 登录成功返回用户信息和token，登录失败不返回
     */
    @PostMapping("/login")
    public ResponseMap login(@RequestBody Map<String, String> params) {
        String username = params.get("username");
        String password = params.get("password");
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return new ResponseMap(WebCode.LOGIN_FAIL);
        }
        User user = new User();
        user.setId(Long.parseLong(username));
        user.setPwd(password);
        user.setUsed(1);
        List<User> users = userService.getUsers(user);
        if (users.size() == 0) {
            return new ResponseMap(WebCode.LOGIN_FAIL);
        }
        ResponseMap response = new ResponseMap();
        response.setCode(WebCode.LOGIN_SUCCESS.getCode());
        String token = JwtUtil.generateToken(String.valueOf(user.getId()));
        response.putValue("name", users.get(0).getName());
        response.putValue("token", token);
        return response;
    }

    /**
     * 注册
     * @param user 注册的信息
     * @return 注册请求是否成功
     */
    @PostMapping("/register")
    public ResponseMap register(@RequestBody User user){
        //mailUtil.sendMessageToAdmin(String.format(REGISTER_FORMAT,user.getId(),user.getName()));
        return userService.inertUser(user) > 0 ? ResponseMap.create(WebCode.REQUEST_SUCCESS) : ResponseMap.create(WebCode.REQUEST_FAIL);
    }



    /**
     * 测试方法
     * @return 用户名
     */
    @RequestMapping("/t")
    public ResponseMap test(){
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        return new ResponseMap(100,name);
    }

}
